package com.rw.tool.util.expression.exception;

import com.rw.tool.util.expression.element.ExpressionElement;
import com.rw.tool.util.string.StringFormatter;

import java.util.List;

/**
 * 后缀表达式异常
 */
public class PostfixPrefixExpressionException extends ExpressionException {
    // 错误位置
    private final int errorIndex;

    // 解析错误的表达式
    private final List<ExpressionElement> elements;

    private static String getErrorMessage(int errorIndex) {
        final String errorMessage = "No matching numbers found! Error index at {}";
        return StringFormatter.format(errorMessage, errorIndex);
    }

    private static String getErrorMessage() {
        return "Cannot have parentheses in Postfix or Prefix Expression!";
    }

    /**
     * 当某一个符号未找到匹配数字时，构造异常
     */
    public PostfixPrefixExpressionException(List<ExpressionElement> elements, int errorIndex) {
        super(getErrorMessage(errorIndex));
        this.errorIndex = errorIndex;
        this.elements = elements;
    }

    /**
     * 当表达式中拥有括号时，构造异常
     */
    public PostfixPrefixExpressionException(List<ExpressionElement> elements) {
        super(getErrorMessage());
        this.errorIndex = -1;
        this.elements = elements;
    }


    /**
     * 获取错误位置，如果为-1则代表表达式中有括号
     */
    public int getErrorIndex() {
        return errorIndex;
    }

    /**
     * 获取错误的后缀表达式
     */
    public List<ExpressionElement> getElements() {
        return elements;
    }
}
